<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <!-- <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary" @click="showAddForm">新增</el-button>
            </el-form-item>
          </el-form> -->
          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item label="">
              <el-input v-model="searchForm.nickName" size="mini" placeholder="请输入工作人员"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="searchForm.name" size="mini" placeholder="请输入项目类型"></el-input>
            </el-form-item>

            <el-form-item label="操作时间:">
              <el-date-picker
                v-model="date.date1"
                size="mini"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-form>



          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form :inline="true" size="medium">
              <el-form-item v-if="this.userRole!=2&&this.userRole!=8">
                <el-button size="mini" type="primary" @click="showAddForm">新增</el-button>
              </el-form-item>
            </el-form>

            <el-form-item>
              <el-button  size="mini" type="primary" @click="search">查询</el-button>
            </el-form-item>
            <!-- <el-form-item>
              <el-button  size="mini" type="primary" @click="clear">清空</el-button>
            </el-form-item> -->
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button size="mini" type="primary" @click="search">刷新</el-button>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="mini" @click="exportExcel">Excel导出</el-button>
            </el-form-item>

          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="项目类型"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="customerName"
        label="业务经理"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="itemCode"
        label="任务单"
        min-width="120">
        <template scope="scope">
          {{scope.row.itemCode}}
          <!-- +'-('+fmtDate(scope.row.carCreateTime)+')' -->
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="name"
        label="任务名称"
        min-width="120">
      </el-table-column> -->
      <el-table-column
        prop="unit"
        label="单位"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="num"
        label="数量"
        min-width="120">
        <template scope="scope">
          {{parseFloat(scope.row.num).toFixed(2)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="userName"
        label="工作人员"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="averageMoney"
        label="金额"
        min-width="120">
        <template scope="scope" >
          {{ToFixed(scope.row.averageMoney)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="note"
        label="备注"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="createUserName"
        label="操作人"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="操作时间"
        min-width="160">
        <template scope="scope">
          {{fmtDate(scope.row.updateTime)}}
        </template>
      </el-table-column>
      <el-table-column v-if="this.userRole==1"
        prop="address"
        label="操作"
        min-width="160">
        <template slot-scope="scope">
          <template >
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="项目类型" label-width="100px" prop="name">
          <!-- <el-select v-model="editForm.name"   placeholder="请选择" style="width: 100%;"
          @change="getUnitPrice">
              <el-option
                v-for="item in TestWorkTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select> -->
            <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="任务单" label-width="100px" prop="carEnterpriseName">
          <el-select v-model="editForm.carEnterpriseName"   placeholder="请选择" style="width: 100%;"
          @change="getUnitPrice">
              <el-option
                v-for="item in TestorderList"
                :key="item.tOrderId"
                :label="item.itemCode+'('+fmtDate(item.createTime)+')'"
                :value="item.tOrderId">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="数量" label-width="100px" prop="num">
          <el-input v-model="editForm.num" type="number" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="金额" label-width="100px" prop="averageMoney">
          <el-input v-model="editForm.averageMoney"  autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="单位" label-width="100px" prop="unit">
          <el-input v-model="editForm.unit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="工作人员" label-width="100px" prop="userName">
          <el-select v-model="editForm.userName"   placeholder="请选择" style="width: 100%;"
          >
              <el-option
                v-for="item in TestUserList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.note" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getTestWorkloadList, addTestWorkload, updateTestWorkload, deleteTestWorkload,getTestWorkTypeList,getTestUserList,getTestorderList} from "../../../api/test_workload.js";
import {getAllTestSiteList} from '../../../api/test_site.js'
import {getToken} from '../../../common/utils/auth.js'
import {getAllUserList,getUser,getAllCarList,getUserRole} from '../../../api/user.js'
import axios from "axios";

export default {
  name: "testWorkload",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      userRole:'',
      date:{
        date1: '',
        date2: '',
      },
      editForm: {
        id: 0,
        carId: '', // 车辆id
        name: '',
        price: '',
        num:'',
        totalPrice:'',
        tOrderId:'',
        unit:'',
        note: '',
        userName:'',
        carEnterpriseName:'',
        averageMoney:'',
        userId: '',
      },
      editRules: {
        name: [{ required: true, message:"请输入项目类型", trigger: 'blur'}],
        carEnterpriseName: [{ required: true, message:"请选择任务单", trigger: 'blur'}],
        averageMoney: [{ required: true, message:"请输入金额", trigger: 'blur'}],
        num: [{ required: true, message:"请输入数量", trigger: 'blur'}],
        unit: [{ required: true, message:"请输入单位", trigger: 'blur'}],
        userName: [{ required: true, message:"请输入单位", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {
        name: '',
        price: '',
        unit:'',
        nickName:'',
        arriveTime1:'',
        arriveTime2:'',
      },
      TestUserList:[],
      TestorderList:[],
      TestWorkTypeList:{
        id: 0,
        name: '',
        price: '',
        unit:'',
      },

      testSiteList:[],
      carId:'',
    }
  },
  computed:{

  },
  mounted() {
    let carId= 0;
    this.carId = carId;

    this.init();

    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/get?_t="+t+"&f=";
  },
  methods: {
    init(){
      getAllTestSiteList().then(res => {
        if(res.code == 1) {
          this.testSiteList = res.data;
        }
      }).catch(res => {

      })
    },

    ToFixed(price){
      if(price!=null&&price!=''){
          return parseFloat(price).toFixed(2)
        }else{
          return parseFloat(0).toFixed(2)
        }
    },

    exportExcel(){
    const loadingDiv = util.showLoading("正在导出EXCEL")

    let param = {
      pageSize: this.pageSize,
      pageNum: this.currentPage,
      arriveTime1:this.searchForm.arriveTime1 ,
      arriveTime2:this.searchForm.arriveTime2 ,
      nickName: this.searchForm.nickName,
      name: this.searchForm.name,
    };

    // param['siteId'] = this.$route.params.id;
    // console.log(param);

    let t = getToken();
    let headers = {"x-token": t};
    axios({
      method: 'post',
      url: this.$adminApiUrl + "/test-workload/excel-workload", // 请求地址

      data: param, // 参数
      headers: headers,
      responseType: 'blob' ,// 表明返回服务器返回的数据类型

    }).then(res=>{
      loadingDiv.close();
      let blob = new Blob([res.data], { type: 'application/xlsx' })
      let url = window.URL.createObjectURL(blob)
      const link = document.createElement('a') // 创建a标签
      link.href = url;
      let timeStr = "";//this.fmtDate(new Date(),"yyyyMMdd_hhmmss");
      link.download = '工作量'+ '.xlsx' // 重命名文件
      link.click()
      URL.revokeObjectURL(url)

    }).catch(err=>{
      // console.log(err);
      loadingDiv.close();
      this.$alert("导出失败,请检查网络", {dangerouslyUseHTMLString:true,type:'warning'})
    });
    },



    isEmpty(val){
      return util.isEmpty(val);
    },

    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },

    showAddForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.last){
        this.editForm[key] = '';
      }

      this.editForm.carId = this.carId;
      this.editForm.id = 0;
      this.editForm.name = '';
      this.editForm.price = '';
      this.editForm.totalPrice = '';
      this.editForm.supplier = '';
      this.editForm.tOrderId = '';
      this.editForm.num = 1;
      this.editForm.carEnterpriseName = '';
      this.editForm.averageMoney = '';
      this.editForm.userList = [];
      this.editForm.costName = '';
      this.editForm.unit = '';
      this.editForm.note = '';
      this.editForm.userId = [];
       this.editForm.userName = '';
      this.editFormVisible = true;
    },
    computed(){
      this.editForm.totalPrice = this.editForm.price*this.editForm.num

    },
    getUnitPrice(){

      for(var i=0;i<this.TestWorkTypeList.length;i++){
        if(this.TestWorkTypeList[i].name == this.editForm.name){
        this.editForm.price = this.TestWorkTypeList[i].price;
        this.editForm.unit = this.TestWorkTypeList[i].unit;
        }
      }

      this.editForm.tOrderId = this.editForm.carEnterpriseName;

    },

    // getTestUser(){

    //   for(var i=0;i<this.TestUserList.length;i++){
    //     if(this.TestUserList[i].nickname == this.editForm.nickname){
    //        this.editForm.nickname = this.TestUserList[i].id
    //     }
    //   }
    // },

    handleEdit(index, row) {


      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.editForm){
        this.editForm[key] = row[key];
      }
      this.editFormVisible = true;
      this.editForm.carEnterpriseName = this.editForm.tOrderId
      this.editForm.userName = this.editForm.userId;


    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateTestWorkload
          if(this.editForm.id == 0){
            func = addTestWorkload
          }
          func(this.editForm).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestWorkload({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      if (util.isNotEmpty(this.date.date1) && this.date.date1.length>=2){
        this.searchForm.arriveTime1 = this.date.date1[0];
        this.searchForm.arriveTime2 = this.date.date1[1];
      }else{
        this.searchForm.arriveTime1 = "";
        this.searchForm.arriveTime2 = "";
      }

      getUserRole().then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.userRole = data.userRole
          // console.log(this.userRole)

        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      });

      getTestWorkloadList({
        arriveTime1:this.searchForm.arriveTime1 ,
        arriveTime2:this.searchForm.arriveTime2 ,
        nickName: this.searchForm.nickName,
        name: this.searchForm.name,
        pageSize: this.pageSize,
        pageNum: pageNum,

      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
          this.last = data.last;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      // getTestWorkTypeList().then(res => {
      //   if(res.code == 0) {
      //     this.$message({
      //       showClose: true,
      //       message: res.msg,
      //       type: 'error'
      //     });
      //   }else if(res.code == 1) {
      //      this.TestWorkTypeList = res.data;
      //   }
      //   loadingDiv.close();
      // }).catch(res => {
      //   loadingDiv.close();
      // })

      getTestUserList().then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
           this.TestUserList = res.data;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      getTestorderList().then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
           this.TestorderList = res.data;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
